package com.pokermind.dse.controller;

import com.pokermind.common.web.ApiResponse;
import com.pokermind.model.dto.*;
import com.pokermind.operator.AdvancedHandOperator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Advanced Hand Management Controller Implements complete poker hand management API following Texas Hold'em business
 * rules Core features: - Unified exception handling and error code system - Complete request parameter validation -
 * Structured logging - Standardized API response format
 *
 * @author PokerMind Team
 */
@RestController
@RequestMapping("/api/hands")
@CrossOrigin(origins = "*")
public class AdvancedHandController extends BaseController {

    private final AdvancedHandOperator advancedHandOperator;

    @Autowired
    public AdvancedHandController(AdvancedHandOperator advancedHandOperator) {
        this.advancedHandOperator = advancedHandOperator;
    }

    /**
     * 5.1.1 Create New Hand POST /hands Function: Initialize new hand record, establish player seats and blind
     * structure Validation: Complete Texas Hold'em business rule validation
     *
     * @param request Create hand request containing all necessary hand configuration
     * @return Successfully created hand information with system-generated record ID and calculated game state
     */
    @PostMapping("/create")
    public ResponseEntity<ApiResponse<CreateHandResponse>> createHand(@RequestBody CreateHandRequest request) {
        CreateHandResponse response = advancedHandOperator.createHand(request);
        return handCreated(response);
    }

    /**
     * 5.1.2 Update Hero Hole Cards PATCH /hands/{hand_record_id}/hero-cards Function: Update Hero player's hole cards
     * in specified hand Validation: Hole cards format and quantity validation
     *
     * @param handRecordId Hand record ID
     * @param request      Request body containing hole cards information
     * @return Update result containing new hole cards information
     */
    @PatchMapping("/{handId}/hero-cards")
    public ResponseEntity<ApiResponse<Map<String, Object>>> updateHeroCards(@PathVariable String handId,
        @RequestBody Map<String, Object> request) {
        @SuppressWarnings("unchecked") List<String> holeCards = (List<String>)request.get("hole_cards");
        String tableId = (String)request.get("table_id"); // V4.7: 添加 table_id 支持

        // Business layer validation and update
        advancedHandOperator.updateHeroCards(handId, tableId, holeCards);

        // Build response data
        Map<String, Object> responseData = new HashMap<>();
        responseData.put("updated", true);
        responseData.put("hero_cards", holeCards);

        return handOperationSuccess(responseData, "hero cards update");
    }

    /**
     * 5.1.3 Street Transition POST /hands/{hand_record_id}/streets Function: Transition hand from current street to
     * next street (preflop → flop → turn → river) Validation: Street transition order and community cards quantity
     * validation
     *
     * @param handRecordId Hand record ID
     * @param request      Street transition request containing target street and community cards
     * @return Transitioned hand state information
     */
    @PostMapping("/{handId}/streets")
    public ResponseEntity<ApiResponse<StreetTransitionResponse>> transitionStreet(@PathVariable String handId,
        @RequestBody StreetTransitionRequest request) {
        StreetTransitionResponse response = advancedHandOperator.transitionToStreet(handId, request);
        return handOperationSuccess(response, "street transition");
    }

    /**
     * 5.2.1 Record Single Action POST /hands/{hand_record_id}/actions Function: Record player action in hand (fold,
     * call, raise, check, etc.) Validation: Action type, amount, turn order and other Texas Hold'em rule validation
     *
     * @param handRecordId Hand record ID
     * @param request      Action request containing player, action type and amount information
     * @return Action record result containing updated game state
     */
    @PostMapping("/{handId}/actions")
    public ResponseEntity<ApiResponse<ActionResponse>> recordAction(@PathVariable String handId,
        @RequestBody ActionRequest request) {
        ActionResponse response = advancedHandOperator.recordAction(handId, request);
        return handOperationSuccess(response, "action recording");
    }

    /**
     * 5.2.2 Complete Hand POST /hands/{hand_record_id}/complete Function: Manually complete specified hand, applicable
     * to following scenarios: - Showdown after River final round - Special situations requiring forced hand termination
     * - Other situations requiring frontend-controlled termination Validation: Completion type, final results and other
     * business rule validation
     *
     * @param handRecordId Hand record ID
     * @param request      Hand completion request containing final results and Hero profit information
     * @return Completion result containing final hand statistics and profit information
     */
    @PostMapping("/{handId}/complete")
    public ResponseEntity<ApiResponse<HandCompletionResponse>> completeHand(@PathVariable String handId,
        @RequestBody HandCompletionRequest request) {
        HandCompletionResponse response = advancedHandOperator.completeHand(handId, request);
        return handOperationSuccess(response, "hand completion");
    }
}